package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.CollegeDao;
import com.lilicould.dao.MajorDao;
import com.lilicould.entity.Majors;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

public class MajorService {

    // 获取所有专业信息
    public String getAllMajors() {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            MajorDao majorDao = sqlSession.getMapper(MajorDao.class);
            return new Gson().toJson(majorDao.getAllMajor());
        } catch (Exception e) {
            return null;
        }
    }

    // 添加一个专业信息
    public String addMajor(Majors major) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            MajorDao majorDao = sqlSession.getMapper(MajorDao.class);
            int result = majorDao.addMajor(major);
            if (result > 0) {
                sqlSession.commit();
                return null;
            } else {
                System.out.println("添加失败");
                return "添加专业信息失败";
            }
        }catch (Exception e) {
            return e.getMessage();
        }
    }

    public String deleteMajor(String majorCode) {
        try(SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            // 获取映射器对象
            MajorDao majorDao = sqlSession.getMapper(MajorDao.class);
            // 调用映射器方法删除专业信息
            int result = majorDao.deleteMajor(majorCode);
            if (result > 0) {
                sqlSession.commit();
                // 删除成功，返回null
                return null;
            } else {
                return "删除专业信息失败";
            }
        } catch (Exception e) {
            return "仅支持删除刚创建未关联其他信息的专业，如实在需要删除，请删除相关联信息后重试，具体原因如下："+e.getMessage();
        }
    }
}
